<template>
  <div class="app-container">
    <div class="bg-container">
      <el-form ref="queryRef" :inline="true" :model="form">
        <el-form-item label="主机：" prop="name">
          <!-- 主机下拉框 -->
          <el-select style="width: 240px;" v-model="form.categoryId" placeholder="请选择主机" @change="handleChange">
            <el-option v-for="item in allComputerList" :key="item.id" :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
          <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
          <el-button icon="Plus" type="primary" @click="handleAdd">添加组件</el-button>
          <el-button icon="Pointer" type="success" @click="handleAddMonitor">一键监控</el-button>
        </el-form-item>
      </el-form>

      <div v-for="(item, index) in categoryList" :key="index">
        <el-row style="margin: auto;">
          <el-col :span="6">
            <el-button :icon="item.showList ? 'ArrowUp' : 'ArrowDown' " type="primary"
                       @click="item.showList = !item.showList">展开组件（{{
                item.name
              }}）
            </el-button>
            <!-- <el-button icon="Edit" plain type="primary"
                       @click="handleUpdate(item)">编辑该组件
            </el-button>
            <el-button icon="Delete" plain type="danger"
                       @click="handleDelete(item)">删除该组件
            </el-button> -->
          </el-col>
          <el-col :span="2">
            <el-tag v-if="item.type == 0" type="success">组件{{ item.componentCount }}</el-tag>
            <el-tag v-else-if="item.type == 1">程序{{ item.componentCount }}</el-tag>
          </el-col>
        </el-row>
        <DeployInfo v-if="item.showList" :cId="form.categoryId" :itemName="item.name" :categoryId="item.id" :type="item.type"/>
        <el-divider/>
      </div>
      <el-empty v-if="categoryList.length == 0" description="暂无数据" />

      <el-pagination
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[3, 5, 7, 10]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; justify-content: flex-end"
          @size-change="bindPageSizeChange"
          @current-change="bindPageCurrentChange"
      />
    </div>

    <!-- 添加组件 -->
    <el-dialog v-model="open" :title="title" append-to-body width="600px">
      <el-form ref="componentCategoryRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加按钮组件 -->
    <popup-host ref="popupHostRef"></popup-host>

  </div>
</template>

<script name="DeployCategory" setup>
import { listAllComputer } from "@/api/computer";
import popupHost from "./components/popupHost.vue";
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {
  addComponentCategory,
  delComponentCategory,
  getComponentCategory,
  listComponentCategory,
  updateComponentCategory,
} from "@/api/componentCategory";
import { putComponentDeployMonitor } from "@/api/computer.js";
import DeployInfo from "@/views/deploy/Info.vue";

const {proxy} = getCurrentInstance();

const categoryList = ref([]);
const open = ref(false);
const loading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const form = reactive({
  categoryId: null,
});

const data = reactive({
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    name: '',
  },
  rules: {
    name: [
      {required: true, message: "分类名不能为空", trigger: ["blur", "change"]}
    ],
    type: [
      {required: true, message: "分类类型不能为空", trigger: ["blur", "change"]}
    ],
  }
});

const {queryParams, rules} = toRefs(data);


const allComputerList = ref([]);
// 查询主机
const getAllComputer = () => {
    listAllComputer().then(response => {
        if (response.data) {
            allComputerList.value = response.data;
            form.categoryId = allComputerList.value[0].id;
            getList();
        }
    });
}


// 一键监控
const handleAddMonitor = () => {
  // const ids = allComputerList.value.map(item => item.id);
  const temArr = []
  categoryList.value.forEach(el => {
    temArr.push(el.componentList)
  })
  const _temArr = temArr.flat();
  if(_temArr.length == 0){
    proxy.$modal.msgWarning("暂无组件,无法一键监控");
    return
  }
  putComponentDeployMonitor(_temArr).then(response => {
    proxy.$modal.msgSuccess("一键监控成功");
  });
}

// 选择主机事件
const handleChange = (val) => {
  form.categoryId = val;
  getList();
}

// 查询数据列表
function getList() {
  loading.value = true;
  const params = {
    pageNo: queryParams.value.pageNo,
    pageSize: queryParams.value.pageSize,
    computerId: form.categoryId,
  }
  listComponentCategory(params).then(response => {
    categoryList.value = response.data.list;
    categoryList.value.forEach(item => {
      item.showList = false
    })
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    creator: null,
    createTime: null,
    updater: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
  };
  proxy.resetForm("componentCategoryRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  proxy.$refs.popupHostRef.openPopup();
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0]
  getComponentCategory({id: id}).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改组件信息";
  });
}

const bindPageSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

const bindPageCurrentChange = (val) => {
  queryParams.value.pageNo = val;
  getList();
}

// 提交按钮
function submitForm() {
  proxy.$refs["componentCategoryRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateComponentCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addComponentCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const id = (row.id ? row.id : null);
  proxy.$modal.confirm('是否确认删除组件信息编号为"' + id + '"的数据项？').then(function () {
    return delComponentCategory({id: id});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  // exportComponentCategory(queryParams.value)
}


onMounted(() => {
  getAllComputer();
});



</script>

<style lang="scss" scoped>
.my-custom-class {
  width: 100%;
}

.blue-button {
  background-color: dodgerblue;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}


.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

</style>